package com.estore.network;

import com.estore.Product;
import com.estore.ProductService;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private ProductService productService;
    private ServerSocket serverSocket;
    private static final int PORT = 8888;

    public EStoreServer() {
        this.productService = new ProductService();
    }

    public void start() {
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，监听端口: " + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接: " + clientSocket.getInetAddress().getHostAddress());

                // 为每个客户端创建新线程处理
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
        } finally {
            if (serverSocket != null && !serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.err.println("关闭服务器失败: " + e.getMessage());
                }
            }
        }
    }

    private void handleClient(Socket clientSocket) {
        ObjectInputStream inputStream = null;
        ObjectOutputStream outputStream = null;

        try {
            // 注意：必须先创建输出流，再创建输入流
            outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
            inputStream = new ObjectInputStream(clientSocket.getInputStream());

            // 读取客户端请求
            String request = (String) inputStream.readObject();
            System.out.println("接收到客户端请求: " + request);

            // 处理请求
            Object response = processRequest(request);

            // 发送响应
            outputStream.writeObject(response);
            outputStream.flush();
            System.out.println("响应已发送给客户端");

        } catch (IOException | ClassNotFoundException e) {
            System.err.println("处理客户端请求时出错: " + e.getMessage());
        } finally {
            // 关闭资源
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
                if (clientSocket != null) clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭连接时出错: " + e.getMessage());
            }
        }
    }

    private Object processRequest(String request) {
        switch (request) {
            case "GET_ALL_PRODUCTS":
                return productService.getAllProducts();
            case "GET_SERVER_INFO":
                return "EStore Server v1.0 - Running on port " + PORT;
            default:
                return "ERROR: Unknown request: " + request;
        }
    }

    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();
        server.start();
    }
}
